package com.ag.admin.service.impl;

import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ag.admin.dao.AdminTbContactDAO;
import com.ag.admin.dao.AdminTbUserDAO;
import com.ag.admin.utils.MD5withSalt;
import com.ag.bean.TbContact;
import com.ag.bean.TbUser;
import com.ag.bean.TbUserRole;
import com.ag.bean.TbUserState;
import com.ag.common.IBaseService;
import com.ag.common.IDUtil;
import com.ag.contactTree.service.LocalTreeService;
import com.ag.dao.TbUserRoleDAO;
import com.ag.dao.TbUserStateDAO;
import com.ag.lzm.dao.TbRoleDAO;
import com.ag.webservice.LwcOAsynchronism;
/**
 * 用户业务逻辑
 * @author 温镇澎
 *
 */
@Service("userServiceImpl")
public class UserServiceImpl implements IBaseService<TbUser, String> {
	private static final Logger logger = Logger
			.getLogger(UserServiceImpl.class);
	
	@Resource(name="LocalTreeService")
	private LocalTreeService localTreeService;
	@Resource(name = "adminTbUserDAO")
	private AdminTbUserDAO userDAO;
	@Resource(name = "TbUserRoleDAO")
	private TbUserRoleDAO userRoleDAO;
	@Resource(name="adminTbContactDAO")
	private AdminTbContactDAO contactDAO;
	@Resource(name="TbUserStateDAO")
	private TbUserStateDAO userStateDAO;
	@Resource(name="LZMTbRoleDAO")
	private TbRoleDAO roleDAO;
	
	
	@Resource(name = "LwcOAsynchronism")
	private LwcOAsynchronism lwcOAsynchronism; //dgm,这是拿来更新树的
	
	@Override
	public boolean delete(String id) {
		TbUser user = this.userDAO.findById(id);
		user.setA(IDUtil.DELETE);
		this.userDAO.attachDirty(user);
		return true;
	}

	@Override
	public boolean delete(TbUser t) {
		return false;
	}

	@Override
	public TbUser findById(String id) {
		return this.userDAO.findById(id);
	}

	@Override
	public boolean save(TbUser t) {
		this.userDAO.save(t);
		return false;
	}

	public boolean save(TbUser user, String selRoles,String selDepts) {
		try{
			MD5withSalt md5ws = new MD5withSalt(user.getUId(), "MD5");
			user.setUPassword(md5ws.encode(user.getUPassword()));
			user.setA(IDUtil.PRESERVE);
			//user.setTbUserState((TbUserState) this.userStateDAO.findAll().get(0));
			this.userDAO.save(user);
			logger.info("selRoles"+selRoles);
			logger.info("selDepts"+selDepts);
			String[] roles = selRoles.split(",");
			for (String r : roles) {
				if (r.length() > 0) {
					TbUserRole ur = new TbUserRole();
					//ur.setId(new TbUserRoleId(r,user.getUId()));
					ur.setTbUser(user);
					ur.setTbRole(roleDAO.findById(r));
					ur.setA(IDUtil.PRESERVE);
					this.userRoleDAO.save(ur);
				}
			}
			logger.info("UId"+user.getUId());
			this.localTreeService.designatedDept(user.getUId(), selDepts.split(","));
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;	

	}
	
	@Override
	public boolean update(TbUser u) {
		return false;
	}
	/**
	 * 
	 * @param user
	 * @param selRoles
	 * @param selDepts
	 * @return
	 */
	public boolean update(TbUser user, String selRoles, String selDepts) {
		try {
			TbUser oldUser = this.userDAO.findById(user.getUId());
//			if (!user.getUPassword().isEmpty()) {
//				MD5withSalt md5ws = new MD5withSalt(oldUser.getUId(), "MD5");
//				oldUser.setUPassword(md5ws.encode(user.getUPassword()));
//			}
			oldUser.setUPhone(user.getUPhone());
			oldUser.setUTel(user.getUTel());
			oldUser.setUFax(user.getUFax());
			oldUser.setUMail(user.getUMail());
			oldUser.setTbUserState(user.getTbUserState());
			this.userDAO.attachDirty(oldUser);
			
			logger.info("selRoles:" + selRoles + "--");
			logger.info("selDepts:" + selDepts + "--");
			if (!selRoles.isEmpty()) {
				Set<TbUserRole> tbUserRoles = oldUser.getTbUserRoles();
				for (TbUserRole userRole : tbUserRoles) {
					this.userRoleDAO.delete(userRole);
				}
				String[] roles = selRoles.split(",");
				for (String r : roles) {
					if (r.length() > 0) {
						TbUserRole ur = new TbUserRole();
						// ur.setId(new TbUserRoleId(r,user.getUId()));
						ur.setTbUser(user);
						ur.setTbRole(roleDAO.findById(r));
						ur.setA(IDUtil.PRESERVE);
						this.userRoleDAO.save(ur);
					}
				}
			}
			if (!selDepts.isEmpty()) {
				this.localTreeService.designatedDept(user.getUId(), selDepts
						.split(","));
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
		lwcOAsynchronism.initRole();
		
		
		
		return true;
	}
	/**
	 * 个人用户修改信息
	 * @param u
	 * @return
	 */
	public boolean updateOne(TbUser u) {
		try {
			TbUser oldUser = this.userDAO.findById(u.getUId());
			oldUser.setUName(u.getUName());
			logger.info("upass"+u.getUPassword());
			if(!u.getUPassword().isEmpty()){
				MD5withSalt md5ws = new MD5withSalt(u.getUId(), "MD5");
				oldUser.setUPassword(md5ws.encode(u.getUPassword()));
			}
			oldUser.setUPhone(u.getUPhone());
			oldUser.setUTel(u.getUTel());
			oldUser.setUFax(u.getUFax());
			oldUser.setUMail(u.getUMail());
			this.userDAO.attachDirty(oldUser);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	/**
	 *                   
	 * @param user       hmk
	 * @param selRoles
	 * @param selDepts
	 * @return
	 */
	public boolean updateExpertUser(TbUser user, String selRoles,String selDepts) {
		System.out.println("fff:"+user.getUId());
		TbUser oldUser = null;
		oldUser = this.userDAO.findByExpertUserID(user.getUId());
		/*
		if (list!=null) {
			oldUser = (TbUser)list.iterator().next();
		}
		*/
		if (oldUser==null) {
			System.out.println("=====null");
		}
		System.out.println("密码："+user.getUPassword());
		System.out.println("旧密码："+oldUser.getUPassword());
		if(!user.getUPassword().isEmpty()){
			MD5withSalt md5ws = new MD5withSalt(user.getUId(), "MD5");
			user.setUPassword(md5ws.encode(user.getUPassword()));
		}else{
			user.setUPassword(oldUser.getUPassword());
		}
		user.setULoginTime(oldUser.getULoginTime());
		user.setA(oldUser.getA());
		user.setB(oldUser.getB());
		user.setC(oldUser.getC());
		this.userDAO.attachDirty(user);
		logger.info("selRoles"+selRoles+"--");
		logger.info("selDepts"+selDepts+"--");
		if(selRoles!=null && selRoles.length()>0){
			Set<TbUserRole> tbUserRoles= oldUser.getTbUserRoles();
			for(TbUserRole userRole : tbUserRoles){
				this.userRoleDAO.delete(userRole);
			}
			String[] roles = selRoles.split(",");
			for (String r : roles) {
				if (r.length() > 0) {
					TbUserRole ur = new TbUserRole();
					//ur.setId(new TbUserRoleId(r,user.getUId()));
					ur.setTbUser(user);
					ur.setTbRole(roleDAO.findById(r));
					ur.setA(IDUtil.PRESERVE);
					this.userRoleDAO.save(ur);
				}
			}
		}
		if(selDepts!=null && selDepts.length()>0){
			logger.info("not");
			this.localTreeService.designatedDept(user.getUId(), selDepts.split(","));
		}
		return false;
	}
	
	/**
	 * 
	 * @param id
	 * @return  hmk 删除专家用户
	 */
	public boolean deleteExpertUser(String id) {
		TbUser user = this.userDAO.findByExpertUserID(id);
		if (user!=null) {
			user.setA(IDUtil.DELETE);
			this.userDAO.attachDirty(user);
		}else{
			System.out.println("===null");
		}
		
		return true;
	}
	
	/**
	 * 
	 * @param id
	 * @return  hmk 查询专家用户(by userID)
	 */
	public TbUser findByExpertID(String id) {
		TbUser user = this.userDAO.findByExpertUserID(id);
		/*
		if (user!=null) {
			user.setA(IDUtil.DELETE);
			this.userDAO.attachDirty(user);
		}else{
			System.out.println("===null");
		}*/
		
		return user;
	}
	
	
	
	public List<TbUser> findAllUser() {
		return this.userDAO.findAll();
	}
	
	public List<TbUserState> fndAllUserState() {
		return this.userStateDAO.findAll();
	}
	
	public boolean checkUId(String uId) {
		String hql = "select count(*) from TbUser u where u.UId = '"+uId+"'";
		int size = ((Long)this.userDAO.checkUId(hql).iterator().next()).intValue();
		logger.info("size="+size);
		if(size!=0){
			return false;
		}else{
			return true;
		}
	}
	
	public List<TbContact> findContactByUName(String UName) {
		String queryString = "from TbContact c join fetch c.tbDept where c.CName = '" + UName+"'";
		return this.contactDAO.findByUName(queryString);
	}


	
}
